import React, {useEffect, useState} from 'react';
import {ImageBackground, ScrollView, StyleSheet, TextInput} from 'react-native';
import {useNavigation, useRoute} from '@react-navigation/native';
import screen from '../../utils/screen';
import Images from '../../images/images';
import {useHeaderHeight} from '@react-navigation/elements';
import LinkButton from '../../components/linkButton';
import {useAppStore} from '../../store/useAppStore';
import {useToast} from '../../components/toast/useToast';

const DeviceName = ()=>{
    const navigation = useNavigation()
    const route = useRoute()
    const headerHeight = useHeaderHeight()
    const toast = useToast()
    const {data,callback} = route.params
    const [name,setName] = useState(data.localName ?? data.name)
    const {addDevice} = useAppStore()


    useEffect(()=>{

    },[])

    const saveDevice = ()=>{

        const localName = name.length ? name : data.name

        let device = {
            ...route.params.data,
            localName
        }

        addDevice(device)
        if(callback){
            callback(localName)
            navigation.goBack()
        }else{
            navigation.popToTop()
        }

    }

    return (
        <ImageBackground
            source={Images.home_bg}
            imageStyle={{width:screen.width,height:'100%'}}
            style={[styles.container ]}>
            <ScrollView
                style={{marginTop:headerHeight}}
                contentContainerStyle={{paddingHorizontal:screen.PIXEL_30,alignItems:'center'}}
            >
                <TextInput value={name} onChangeText={setName} maxLength={20} style={styles.input}/>

                <LinkButton
                    style={{marginTop:screen.PIXEL_100}}
                    title={'完成'}
                    onPress={saveDevice}
                />
            </ScrollView>
        </ImageBackground>
    )
}
export default DeviceName
const styles = StyleSheet.create({
    container:{
        flex: 1
    },
    input:{
        width:'100%',height:screen.PIXEL_88,backgroundColor:'#fff',borderRadius:screen.PIXEL_20,
        paddingHorizontal:screen.PIXEL_20,marginTop:screen.PIXEL_30
    }
})
